package com.atguigu.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.pojo.dto.ExcelDictDto;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;


/**
 * @author lwm1435@163.com
 * @date 2022-01-24 11:53
 * @description
 */
@Slf4j
@NoArgsConstructor
public class ExcelDictDtoListener extends AnalysisEventListener<ExcelDictDto> {
    //临时容器
    private final List<ExcelDictDto> temp = new ArrayList<>(BATCH_COUNT);
    //多少数量开始批量插入
    private static final Integer BATCH_COUNT = 5;
    //mapper接口
    private DictMapper dictMapper;

    //有参构造赋值接口层
    public ExcelDictDtoListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    //读取一行调用一次该方法
    @Override
    public void invoke(ExcelDictDto excelDictDto, AnalysisContext analysisContext) {
        temp.add(excelDictDto);
        log.info("解析到一行数据：{}",excelDictDto);
        //执行批量添加
        if (temp.size() >= BATCH_COUNT) {
            insertBatch();
        }
    }
    //所有数据读取完毕
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //如果有数据最后再执行一次批量添加
        if (!temp.isEmpty()){
            insertBatch();
        }
    }

    //批量添加
    private void insertBatch() {
        log.info("执行批量插入");
        dictMapper.insertBatch(temp);
        log.info("批量插入完成");
        temp.clear();
    }
}
